/**
 * Computer Network, Programming Assignment #2
 * 
 * FileReceiver Class
 * 
 * File receiver application, use GPD's gSocket to receive file transfer from a specific grid point
 * 
 * @author Yancheng Li
 *
 */

import java.io.*;
import java.net.Socket;


public class FileReceiver {
	public static void main(String[] args) {
		
		DataInputStream sin = new DataInputStream(new BufferedInputStream(System.in));
		String line = "";
		help();
		while(line.compareTo("exit") != 0){
			try {
				System.out.print("\n>>");
				
				line = sin.readLine();
				
				String [] list = line.split(" ");
				
				if(list.length > 5){
					System.out.println("Error command");					
				}
										
				
				if(list[0].compareTo("receive") == 0){
					
					int x = Integer.valueOf(list[1]);
					int y = Integer.valueOf(list[2]);
					int port = Integer.valueOf(list[3]);
					Socket socket = gSocket.listenTo(new Point(x, y), port);
					saveFile(socket, x, y, port, list[4]);
					continue;
				}
				
				if(list[0].compareTo("help") == 0){
					
					help();
					continue;
				}
				PSPUtil.print("Error command", true);
				
				
			} catch (Exception e) {

				e.printStackTrace();
			}
		}
		
		
	}
	
	
	// save to a specific file
	
	public static void saveFile(Socket socket, int x, int y, int port, String filename){
		try {
			PSPUtil.print("Receiving file start", true);
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 								
		
			FileWriter fstream = new FileWriter(filename);
			BufferedWriter writer = new BufferedWriter((fstream));

			
			char[] data = new char[2048];
			char[] num = new char[4];
			
			while(true)
			{
							
				int readLength = in.read(data, 0, 4);
				
				if(readLength <= 0)
					break;
				for(int i = 0; i < 4; i++)
					num[i] = data[i];						
				
				int length = Integer.parseInt(new String(num), 16);
				in.read(data, 4, length - 4);			
				
				GPDatagram packet = new GPDatagram(data);
				
				PSPUtil.print("Got packet \n" + packet, true);
				
				
				writer.write(packet.getPayload(), 0, packet.getLength() - 16);
				
				Thread.sleep(100);
				if(packet.getLength() <= 16)
					break;
			}
			
			in.close();
			socket.close();
			writer.close();
			PSPUtil.print("Receiving file complete", true);
						
		} catch (Exception e) {
			e.printStackTrace();			
		}		
	}
	
	public static void help(){
		System.out.println("======================================");
		System.out.println("Command List:");
		System.out.println("[1]receive\n receive dst-x dst-y dst-port fileToSaveAs");		
		System.out.println("[2]help:\n print help info");
		System.out.println("======================================");
	}
}
